package com.adnaan.backend.controller;

import com.adnaan.backend.common.exception.BizException;
import com.adnaan.backend.common.utils.R;
import com.adnaan.backend.common.utils.SecurityUtils;
import com.adnaan.backend.entity.LoginUserVo;
import com.adnaan.backend.entity.SysUser;
import com.adnaan.backend.service.SysUserService;
import com.alibaba.fastjson2.JSON;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * author: adnaan
 * create: 2024-05-01 17:06
 * Description:
 */
@Tag(name = "登录接口", description = "登录相关功能")
@RestController
@RequestMapping("/api/login")
public class LoginController extends BaseController {

    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    private String generateToken(SysUser user) {
        String baseToken = user.getRole() + "_";
        String uuidToken = UUID.randomUUID().toString().replace("-", "");
        return baseToken + uuidToken;
    }

    private R loginValidate(String username, String password, String role) {
        SysUser sysUser = sysUserService.selectByUsername(username);
        if (sysUser == null) {
            return R.error("该用户不存在");
        }
        if (sysUser.getStatus().equals("0")) {
            return R.error("该用户已被禁用");
        }

        boolean ok = SecurityUtils.matchesPassword(password, sysUser.getPassword());
        if (!ok) {
            return R.error("登录失败");
        }
        if (!sysUser.getRole().equals(role)) {
            return R.error("该用户没有权限");
        }

        String token = generateToken(sysUser);
        stringRedisTemplate.opsForValue().set(token, JSON.toJSONString(sysUser), 1, TimeUnit.HOURS);
        String json = stringRedisTemplate.opsForValue().get(token);
        SysUser userInfo = JSON.parseObject(json, SysUser.class);
        if (userInfo != null) {
            userInfo.setToken(token);
        } else {
            return R.error(500, "登录失败");
        }
        return R.success("登录成功").put("data", userInfo);
    }

    @Operation(summary = "管理员登录")
    @PostMapping("/sys_login")
    public R sys_login(@RequestBody LoginUserVo loginUserVo) {
        if (loginUserVo.getUsername() == null || loginUserVo.getPassword() == null) {
            return R.error("用户名或密码不能为空");
        }
        return loginValidate(loginUserVo.getUsername(), loginUserVo.getPassword(), "admin");
    }

    @Operation(summary = "用户登录")
    @PostMapping("/user_login")
    public R user_login(@RequestBody LoginUserVo loginUserVo) {
        if (loginUserVo.getUsername() == null || loginUserVo.getPassword() == null) {
            return R.error("用户名或密码不能为空");
        }
        return loginValidate(loginUserVo.getUsername(), loginUserVo.getPassword(), "user");
    }

    @Operation(summary = "退出登录")
    @PostMapping("/logout")
    public R logout(HttpServletRequest request) {
        if(this.getCurUser() != null) {
            String token = request.getHeader("Authorization");
            stringRedisTemplate.delete(token);
            System.out.println(token);
            return R.success("退出成功");
        }else {
            throw new BizException(500, "数据不存在");
        }
    }
}
